//
//  RefreshView.swift
//  SwiftWB
//
//  Created by 钟清 on 17/4/6.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit

class RefreshView: UIView {
    /* 下载圆圈 */
    @IBOutlet weak var loadingImageView: UIImageView!
    /* 提示视图 */
    @IBOutlet weak var tipView: UIView!
    /* 提示箭头 */
    @IBOutlet weak var arrowImageView: UIImageView!
    /* 快速获取刷新视图 */
    class func refreshView() -> RefreshView {
        return (NSBundle.mainBundle().loadNibNamed("RefreshView", owner: nil, options: nil).first as! RefreshView)
    }
    
    // MARK: - 外部控制方法
    /* 旋转箭头 */
    func rotationArrow(flag: Bool) {
        /* 旋转方向，依次为就近、顺时针 */
        var angle: CGFloat = flag ? -0.01 : 0.01
        angle += CGFloat(M_PI)
        UIView.animateWithDuration(1.0) { 
            self.arrowImageView.transform = CGAffineTransformRotate(self.arrowImageView.transform, angle)
        }
    }
    /* 显示加载视图 */
    func startLoadingView() {
        /* 隐藏箭头 */
        tipView.hidden = true
        /* 判断 */
        if let _ = loadingImageView.layer.animationForKey("zq") { // 已有动画，则直接返回
            return
        }
        /* 创建动画 */
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.duration = 3.0
        anim.repeatCount = MAXFLOAT
        loadingImageView.layer.addAnimation(anim, forKey: "zq")
    }
    /* 隐藏加载视图 */
    func stopLoadingView() {
        tipView.hidden = false
        loadingImageView.layer.removeAllAnimations()
    }
    
}

class SWRefreshControl: UIRefreshControl {
    override init() {
        super.init()
        /* 添加子控件 */
        addSubview(refreshView)
        /* 布局 */
        refreshView.center = self.center
        refreshView.sizeToFit()
        /* 监听 */
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit
    {
        removeObserver(self, forKeyPath: "frame")
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoadingView()
    }
    
    /* 标记 */
    var rotationFlag = false
    // MARK: - 内部控制方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        /* 根据y值变化进行提示 */
        // ZQLog(frame)
        if frame.origin.y == 0 || frame.origin.y == -64 { // 过滤初始数据
            return
        }
        /* 是否触发下拉刷新 */
        if refreshing {
            refreshView.startLoadingView()
            return
        }
        if frame.origin.y < -100 && !rotationFlag {
            rotationFlag = true
            ZQLog("往上旋转")
            refreshView.rotationArrow(rotationFlag)
        } else if frame.origin.y > -100 && rotationFlag {
            rotationFlag = false
            ZQLog("往下旋转")
            refreshView.rotationArrow(rotationFlag)
        }
    }
    
    // MARK: - Lazy
    private lazy var refreshView: RefreshView = RefreshView.refreshView()
}
